﻿
Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling

Imports AxMicrosoft.Office.Interop.VisOcx
Imports Microsoft.Office.Interop.Visio
Imports Microsoft.Office.Interop.VisOcx
Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop

Imports System.Data
Imports System.Data.OleDb
Imports System.Windows.Forms

Imports Microsoft.Office.Interop.Excel

Imports System
Imports System.IO
Imports Microsoft.Reporting.WinForms

Imports visRackAppConnectivity.clsDC_RackData


Public Class frmAppConnect


#Region " Properties and Declarations "



    Private visioEventSink As clsEventSink
    Private _clsVisio As clsVisioSupport

    Private _clsAppConn As clsAppConnections
    Private _clsApps As clsAttrApplications

    '
    Private _clsData As clsDC_RackData
    ' dictSolApps is a list of applications in current selected solution
    ' app key and name
    Private dictSolApps As Dictionary(Of Int32, String)
    ' dictPage Solutions is a list of current solutions on the page (really a track of layers)
    ' solution key and solution name
    Private dictPageSolutions As Dictionary(Of Int32, String)
    ' dictPageApplications is a list of applications on the page
    ' shapeid and application Key
    Private dictPageApplications As Dictionary(Of Short, Int32)
    ' dictTables is a list of the tables we will use in this solution
    ' enumTable value and the exported table name
    Private dictTables As Dictionary(Of Int16, String)

    Const stencilNameU As String = "SERVER_U.VSS"
    Const masterServerNameU As String = "Server"
    Const masterContainerStencilU As String = ""
    Const masterContainerNameU As String = "Container 3"
    Const dblContainerHeight As Double = 2
    Const dblContainerWidth As Double = 3
    ' start .75 from left side of page and the top
    Const dblContainerMargin As Double = 1.5



    '********* visio snippet vb.net visXXXX ******************
    Private _drawingApplication As Microsoft.Office.Interop.Visio.Application
    Public Property drawingApplication() As Microsoft.Office.Interop.Visio.Application
        Get
            Return Me._drawingApplication
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Application)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "drawingApplication is Null.")
            End If
            Me._drawingApplication = value
        End Set
    End Property


    '********* visio snippet vb.net visXXXX ******************
    Private _drawingDocument As Microsoft.Office.Interop.Visio.Document
    Public Property drawingDocument() As Microsoft.Office.Interop.Visio.Document
        Get
            Return Me._drawingDocument
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Document)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "drawingDocument is Null.")
            End If
            Me._drawingDocument = value
        End Set
    End Property


    '********* visio snippet vb.net visXXXX ******************
    Private _drawingWindow As Microsoft.Office.Interop.Visio.Window
    Public Property drawingWindow() As Microsoft.Office.Interop.Visio.Window
        Get
            Return Me._drawingWindow
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Window)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "drawingWindow is Null.")
            End If
            Me._drawingWindow = value
        End Set
    End Property

    '********* visio snippet vb.net visXXXX ******************
    Private _drawingPage As Microsoft.Office.Interop.Visio.Page
    Public Property drawingPage() As Microsoft.Office.Interop.Visio.Page
        Get
            Return Me._drawingPage
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Page)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "drawingPage is Null.")
            End If
            Me._drawingPage = value
        End Set
    End Property


    '********* visio snippet vb.net visXXXX ******************
    Private _drawingControl As AxMicrosoft.Office.Interop.VisOcx.AxDrawingControl
    Public Property drawingControl() As AxMicrosoft.Office.Interop.VisOcx.AxDrawingControl
        Get
            Return Me._drawingControl
        End Get
        Set(ByVal value As AxMicrosoft.Office.Interop.VisOcx.AxDrawingControl)
            Me._drawingControl = value
        End Set
    End Property

    Private m_currSolution As Int32
    Private Property _CurrSolution As Int32
        Get
            Return Me.m_currSolution
        End Get
        Set(ByVal value As Int32)
            Me.m_currSolution = value
        End Set
    End Property


    Private m_clsReporting As visRackAppConnectivity.clsDC_RackReporting
    Private Property _clsReporting As visRackAppConnectivity.clsDC_RackReporting
        Get
            Return m_clsReporting
        End Get
        Set(ByVal value As visRackAppConnectivity.clsDC_RackReporting)
            m_clsReporting = value
        End Set
    End Property

#End Region

#Region " Constructor "


    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

        Try

            drawingControl = AxDrawingControl

            InitTheDrawingControl()

            initializeEventSink()

            ' this will use the mouse action as a menu inside the drawing
            AddHandler drawingWindow.MouseUp, AddressOf mouseUp_EventHandler

            _clsVisio = New clsVisioSupport()
            _clsVisio.drawingApplication = drawingApplication

            _clsData = New clsDC_RackData
            _clsData.drawingApplication = drawingApplication

            ' load our stencil
            Dim blnLoaded As Boolean = False
            blnLoaded = _clsVisio.TestStencilLoaded(drawingApplication, stencilNameU)
            If blnLoaded = False Then
                Me.drawingApplication.Documents.OpenEx(stencilNameU, _
                    (CShort(Microsoft.Office.Interop.Visio. _
                        VisOpenSaveArgs.visOpenHidden) + _
                    CShort(Microsoft.Office.Interop.Visio. _
                        VisOpenSaveArgs.visOpenRO)))
            End If


            dictTables = New Dictionary(Of Int16, String)
            ' the three tables that we will work with in this solution
            dictTables.Add(clsDC_RackData.DC_RackTables.tblAppConnection, "dbo_tblAppConnections")
            dictTables.Add(clsDC_RackData.DC_RackTables.tblAppSolution, "dbo_tblAppSolutions")
            dictTables.Add(clsDC_RackData.DC_RackTables.tblAttrApplication, "dbo_tblAttrApplications")

            ' load from excel
            'loadDictionariesFromPage("excel")
            ' load based on the current menu selection (which defaults to the xml files because of form layout)
            loadDictionariesFromPage()



            ' now the report viewer control stuff (has to be fired after draw components because it requires the data to have been loaded)
            '
            rptViewer.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Local

            Dim dtTemp As System.Data.DataTable = New System.Data.DataTable
            ' get a copy of the solutions table
            Try
                dtTemp = _clsData.m_ds.Tables(DC_RackTables.tblAppSolution.ToString).Copy
            Catch rdTemp As Exception
                Exit Sub
            End Try

            ' clear any existing reporting class
            _clsReporting = Nothing
            ' load the component report
            _clsReporting = New visRackAppConnectivity.clsDC_RackReporting _
                    (Me.rptViewer, _
                    _clsReporting.baseReports.rptAppSolutionsAll, _
                    dtTemp)
            _clsReporting._LocalViewer.RefreshReport()


        Catch rpt As ReportViewerException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(rpt, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub


    '********* visio snippet vb.net visXXXX ******************
    Private Const defaultDocumentName As String = "DrawExampleDocument"
    Private Const defaultPageName As String = "DrawExample"

    Private Sub InitTheDrawingControl()

        Try

            '
            ' get the pointers
            '
            ' make sure the control does not change the pagesizebehavior
            Me.drawingControl.PageSizingBehavior = VisPageSizingBehaviors.visNeverResizePages

            Me.drawingWindow = Me.drawingControl.Window
            Me.drawingWindow.Activate()
            Me.drawingApplication = Me.drawingControl.Window.Application

            Me.drawingDocument = Me.drawingControl.Document
            Dim docSheet As Visio.Shape = Me.drawingDocument.DocumentSheet
            docSheet.NameU = defaultDocumentName
            Me.drawingDocument.DiagramServicesEnabled = VisDiagramServices.visServiceVersion140

            Me.drawingPage = Me.drawingControl.Window.Page
            Me.drawingPage.NameU = defaultPageName
            drawingWindow.Page = drawingPage

            Me.drawingApplication.Application.Settings.EnableAutoConnect = False
            Me.drawingApplication.OnDataChangeDelay = -2

            Me.drawingWindow.ShowGrid = False
            Me.drawingWindow.ShowPageTabs = False
            Me.drawingWindow.ShowRulers = False
            Me.drawingWindow.ShowScrollBars = True


        Catch com As COMException
            ' add com exception handler here

            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If


        Catch ex As Exception
            ' add exception handler here

            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If


        End Try

    End Sub


    '********* visio snippet vb.net visXXXX ******************
    Private Sub initializeEventSink()

        Dim targetDocument As Document
        Dim targetApplication As Microsoft.Office.Interop.Visio.Application

        Try

            ' Release the previous event sink.
            visioEventSink = Nothing

            ' Create an event sink to hook up events to the Visio
            ' application and document.
            visioEventSink = New clsEventSink()
            targetApplication = DirectCast(drawingControl.Window.Application, Microsoft.Office.Interop.Visio.Application)
            targetDocument = DirectCast(drawingControl.Document, Document)

            visioEventSink.AddAdvise(targetApplication, targetDocument)

            ' Listen to shape add events from the Visio event sink.
            ' onAddShape will be called when a shape is added.
            AddHandler visioEventSink.OnShapeAdd, AddressOf onAddShape

            ' Listen to shape delete events from the Visio event sink.
            ' onDeleteShape will be called when a shape is deleted.
            AddHandler visioEventSink.OnShapeDelete, AddressOf onDeleteShape

            ' Listen to marker events raised when the user double-clicks a shape.
            ' OnShapeDoubleClick will be called when the user double-clicks
            ' a shape whose double-click event runs the QueueMarkerEvent addon.
            ' =RUNADDONWARGS("QueueMarkerEvent","/dc_rack /cmd=1")
            AddHandler visioEventSink.OnShapeDoubleClick, AddressOf onShapeDoubleClick



        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try
    End Sub


#End Region

#Region " Event Handlers "

    '********* visio snippet vb.net visXXXX ******************
    Private Sub onAddShape(ByVal vsoShape As Visio.Shape, ByVal e As EventArgs)

        Try

        Catch com As COMException
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub


    '********* visio snippet vb.net visXXXX ******************
    Private Sub onDeleteShape(ByVal vsoShape As Visio.Shape, ByVal e As EventArgs)

        Try

        Catch com As COMException
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub


    '********* visio snippet vb.net visXXXX ******************
    Private Sub onShapeDoubleClick(ByVal sender As Object, ByVal e As EventArgs)

        Dim visShape As Visio.Shape = DirectCast(sender, Microsoft.Office.Interop.Visio.Shape)

        Try


            MsgBox(visShape.Text.ToString)

        Catch com As COMException
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

#End Region

#Region " Methods "

    '
    '
    '
    Private Sub loadSolutionApplicationsData(ByVal strSolution As String)

        Dim intAppSolKey As Int32 = -1
        Dim intAppAKey As Int32
        Dim intAppBKey As Int32

        If dictSolApps Is Nothing Then
            dictSolApps = New Dictionary(Of Int32, String)
        Else
            dictSolApps = Nothing
            dictSolApps = New Dictionary(Of Int32, String)
        End If


        Try

            ' first get the solution Key so that we can look for connections
            Dim solutionQuery = From solution In _clsData.m_ds.Tables(dc_racktables.tblAppSolution.ToString).AsEnumerable() _
                        Where solution!appsolName = strSolution _
                        Select solution

            'execute and find only one solution in the table with that key
            If solutionQuery.Count = 1 Then
                For Each s In solutionQuery
                    intAppSolKey = s.Item("appsolKey")
                    _CurrSolution = s.Item("appsolKey")
                Next s
            Else
                Exit Sub
            End If

            '
            ' get a list of unique application keys for the selected solution
            '
            Dim connectionQuery = From connects In _clsData.m_ds.Tables(dc_racktables.tblAppConnection.ToString).AsEnumerable() _
                                  Where connects!appconSolKey = _CurrSolution _
                                  Select connects

            If 0 < connectionQuery.Count Then
                For Each c In connectionQuery
                    intAppAKey = c.Item("appconAppAKey")
                    intAppBKey = c.Item("appconAppBKey")
                    If dictSolApps.ContainsKey(intAppAKey) = False Then
                        dictSolApps.Add(intAppAKey, "")
                    End If
                    If dictSolApps.ContainsKey(intAppBKey) = False Then
                        dictSolApps.Add(intAppBKey, "")
                    End If
                Next c
            Else
                Exit Sub
            End If

            '
            ' now search out the application names
            '
            Dim applicationQuery = From application In _clsData.m_ds.Tables(DC_RackTables.tblAttrApplication.ToString).AsEnumerable() _
                                  Select application

            If 0 < applicationQuery.Count Then
                lstApplications.Items.Clear()
                For Each a In applicationQuery
                    intAppAKey = a.Item("appKey")
                    If dictSolApps.ContainsKey(intAppAKey) = True Then
                        dictSolApps.Item(intAppAKey) = a.Item("appName")
                        lstApplications.Items.Add(a.Item("appName"))
                    End If
                Next a
            Else
                Exit Sub
            End If


        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub



    '
    ' pass in a listbox control and clear all selections
    '
    Private Sub clearListSelections(ByVal ctrlList As System.Windows.Forms.ListBox)
        Try


            ctrlList.BeginUpdate()

            For x = 0 To ctrlList.Items.Count - 1
                ctrlList.SetSelected(x, False)
            Next x

            ctrlList.EndUpdate()


        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try
    End Sub

    '
    ' go through the currently selected solution and remove applications from the appropriate
    ' solution layer, test to see if the application layer count is 0 and delete the shape if 
    ' it is not flagged for any layer, then delete the layer
    '
    Private Function deleteSolutionLayer _
        (ByVal strSolution As String) _
        As Boolean


        Dim visLayer As Visio.Layer = Nothing
        Dim visShape As Visio.Shape = Nothing

        Dim blnReturn As Boolean = False

        Try

            If dictPageSolutions.ContainsValue(strSolution) = True Then
                Dim intAppSolKey As Int32 = -1
                ' first get the solution Key so that we can look for connections
                Dim solutionQuery = From solution In _clsData.m_ds.Tables(dc_racktables.tblAppSolution.ToString).AsEnumerable() _
                            Where solution!appsolName = strSolution _
                            Select solution

                'execute and find only one solution in the table with that key

                If solutionQuery.Count = 1 Then
                    For Each s In solutionQuery
                        intAppSolKey = s.Item("appsolKey")
                        Exit For
                    Next s

                    ' first the connections, since they may be on multiple layers
                    removeSolutionConnections(strSolution, intAppSolKey)

                    removeShapesFromSolutionLayer(strSolution)

                    _clsVisio.removeEmptyContainers()

                    ' get the solution layer
                    Try
                        visLayer = Me.drawingPage.Layers.Item(strSolution)
                    Catch
                    End Try
                    ' delete the solution layer
                    If visLayer IsNot Nothing Then
                        ' unlock it just in case
                        visLayer.CellsC(VisCellIndices.visLayerLock).FormulaU = "0"
                        ' delete it
                        visLayer.Delete(1)
                    End If

                    ' remove the solution layer from the page dictionary
                    If dictPageSolutions.ContainsKey(intAppSolKey) = True Then
                        dictPageSolutions.Remove(intAppSolKey)
                    End If

                    blnReturn = True
                End If
                'end test for solution layer on page
            End If



        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


        ' clear the current solution applications dictionary
        dictSolApps = Nothing
        dictSolApps = New Dictionary(Of Int32, String)
        ' clear the selected solutions
        clearListSelections(lstSolutions)
        ' clear the applications list
        lstApplications.Items.Clear()

        layoutContainers()

        Return blnReturn

    End Function

    '
    ' remove shape from layer, if layer count is 0 then remove from page dictionary as well
    '
    Private Sub removeShapesFromSolutionLayer _
        (ByVal strSolution As String)


        _clsVisio.drawingWindow = drawingControl.Window

        Try

            Dim intLayers As Integer = 0

            Dim visShape As Visio.Shape
            Dim intIndex As Integer = 0
            Dim intShapes As Integer = Me.drawingPage.Shapes.Count
            For intIndex = intShapes To 1 Step -1
                visShape = Me.drawingPage.Shapes(intIndex)

                _clsVisio.RemoveShapeFromLayer(Me.drawingPage, visShape, strSolution, True)

                intLayers = visShape.LayerCount
                If intLayers = 0 Then

                    ' if the shape id is in the page applications dictionary then
                    ' remove it from the list
                    If dictPageApplications.ContainsKey(visShape.ID) = True Then
                        dictPageApplications.Remove(visShape.ID)
                    End If

                    _clsVisio.removeShapeFromContainers(visShape.ID)

                    System.Windows.Forms.Application.DoEvents()
                    If visShape IsNot Nothing Then
                        visShape.Delete()
                    End If

                End If

            Next intIndex


        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    '
    '
    Private Sub removeSolutionConnections _
                (ByVal strSolution As String, _
                 ByVal intSolKey As Int32)

        Try

            Dim intLayer As Integer = 0
            Dim layerShape As Integer = 0
            Dim visShape As Visio.Shape
            Dim intIndex As Integer = 0
            Dim intShapes As Integer = Me.drawingPage.Shapes.Count

            _clsVisio.drawingWindow = drawingControl.Window

            For intIndex = intShapes To 1 Step -1
                visShape = Me.drawingPage.Shapes(intIndex)
                ' if the shape is a connector for this solution - note in v2010 appears to be case sensitive....
                If visShape.CellExists("prop.appconSolKey", False) = True Then
                    layerShape = CInt(visShape.Cells("prop.appconSolKey").ResultIU)
                    _clsVisio.RemoveShapeFromLayer(Me.drawingPage, visShape, strSolution, True)
                    If visShape.LayerCount = 1 Then
                        Dim currentLayer As Visio.Layer = Nothing
                        Try
                            currentLayer = visShape.Layer(1)
                        Catch
                        End Try
                        ' a timing issue that the code for the remove shape returns faster than
                        ' visio gets the job done (ie the layer count is wrong and should be zero
                        If currentLayer Is Nothing _
                            Or currentLayer.NameU.ToString = strSolution Then
                            visShape.Delete()
                            GoTo NextConn
                        End If
                    End If
                    ' if it is on the layer
                    If visShape.LayerCount = 0 Then
                        visShape.Delete()
                        GoTo NextConn
                    End If
                    ' if the layer remove stuff does not get it then brute force
                    If layerShape = intSolKey Then
                        visShape.Delete()
                    End If
                End If
                System.Windows.Forms.Application.DoEvents()
NextConn:   Next intIndex

        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try
    End Sub


    '
    ' pass in a selected shape's name and prefix and load up an item report
    ' the name prefix is the field name for the key 
    '
    Private Sub loadItemReport(ByVal strNode As String)


        Dim dtWork As System.Data.DataTable = Nothing

        Try


            Dim dtWorkName As String = ""

            _clsReporting._LocalViewer = Me.rptViewer
            _clsReporting._LocalViewer.Reset()
            _clsReporting._LocalViewer.LocalReport.DataSources.Clear()
            _clsReporting._DataSource = "Uninitialized"

            Select Case LCase(strNode)

                Case "appkey"
                    ' component node
                    _clsReporting.initReports(_clsReporting.baseReports.rptApplicationsAll)
                    dtWork = _clsData.m_ds.Tables(DC_RackTables.tblAttrApplication.ToString).Copy
                    dtWorkName = DC_RackTables.tblAttrApplication.ToString
                    Exit Select

                Case "appsolkey"
                    ' component root sublocation data
                    _clsReporting.initReports(_clsReporting.baseReports.rptAppSolutionsAll)
                    dtWork = _clsData.m_ds.Tables(DC_RackTables.tblAppSolution.ToString).Copy
                    dtWorkName = DC_RackTables.tblAppSolution.ToString
                    Exit Select

                Case ("appconnkey")
                    ' network link
                    _clsReporting.initReports(_clsReporting.baseReports.rptAppConnectionsAll)
                    dtWork = _clsData.m_ds.Tables(DC_RackTables.tblAppConnection.ToString).Copy
                    dtWorkName = DC_RackTables.tblAppConnection.ToString
                    Exit Select


                Case Else

                    Exit Sub

            End Select


            ' let the system catch up
            System.Windows.Forms.Application.DoEvents()

            If dtWork Is Nothing Then
                MsgBox(strNode & " dtWork is nothing")
                Exit Sub
            End If
            If dtWork.Rows.Count < 1 Then
                MsgBox(strNode & " dtWork is empty")
                Exit Sub
            End If


            _clsReporting._DataTable = dtWork.Copy
            _clsReporting._DataTable.TableName = dtWorkName
            _clsReporting.createLocalReport()
            _clsReporting._LocalViewer.Refresh()
            _clsReporting._LocalViewer.RefreshReport()


        Catch sql As SqlException
            '********* visio snippet vb.net vis0057vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(sql, "Database Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        dtWork = Nothing


    End Sub



#End Region

#Region " External get/save "



    ' 
    ' when loading a page (either initially or from file load) build the dictionaries
    '
    Private Sub loadDictionariesFromPage(Optional ByVal strSource As String = "xml")

        Try

            _clsData = Nothing
            _clsData = New clsDC_RackData()
            _clsData.drawingApplication = drawingApplication
            _clsData.drawingDocument = drawingDocument

            Select Case strSource
                Case "sql"
                    ' load our three tables
                    _clsData.loadAppConnTable()
                    _clsData.loadAppSolTable()
                    _clsData.loadAppTable()
                    Exit Select
                Case "excel"
                    Dim dtTemp As System.Data.DataTable = Nothing
                    Dim dictTemp As Dictionary(Of Int16, String) = New Dictionary(Of Int16, String)

                    ' read the worksheet list into a local dictionary
                    dictTemp = readExcelWorksheetList(My.Settings.path_custom_data & My.Settings.custom_workbook)
                    Dim blnContains As Boolean = True
                    ' are there enough worksheets
                    If 3 <= dictTemp.Count Then
                        For Each kvp In dictTables
                            If dictTemp.ContainsValue(kvp.Value) = False Then
                                blnContains = False
                            End If
                        Next kvp
                    Else
                        MsgBox("Not enough worksheets for this solutions")
                        Exit Sub
                    End If

                    If blnContains = False Then
                        MsgBox("Could not find all necessary worksheets")
                        Exit Sub
                    End If

                    ' now read the worksheets into the tables
                    ' the keyvalue pairs are the table index, and the modified table name
                    For Each kvp In dictTables
                        dtTemp = readExcelWorksheet(My.Settings.path_custom_data & My.Settings.custom_workbook, kvp.Value)

                        Select Case kvp.Key
                            Case DC_RackTables.tblAttrApplication
                                _clsData.loadAppTable(dtTemp)
                            Case DC_RackTables.tblAppConnection
                                _clsData.loadAppConnTable(dtTemp)
                            Case DC_RackTables.tblAppSolution
                                _clsData.loadAppSolTable(dtTemp)
                        End Select
                    Next kvp
                    Exit Select

                Case Else
                    ' the xml default 
                    Dim xmlDataSet As System.Data.DataSet = Nothing
                    If xmlDataSet Is Nothing Then
                        xmlDataSet = New System.Data.DataSet
                    Else
                        xmlDataSet = Nothing
                        xmlDataSet = New System.Data.DataSet
                    End If

                    xmlDataSet.Locale = System.Globalization.CultureInfo.CurrentCulture

                    ' Read the xml data file.
                    Dim dataFilename As String = My.Settings("xmlAppConnections")
                    If File.Exists(My.Settings.path_custom_data & dataFilename) = True Then
                        xmlDataSet.ReadXml(My.Settings.path_custom_data & dataFilename, System.Data.XmlReadMode.ReadSchema)
                    Else
                        MsgBox(dataFilename & " does not exist ")
                        Exit Sub
                    End If
                    dataFilename = My.Settings("xmlAppSolutions")
                    If File.Exists(My.Settings.path_custom_data & dataFilename) = True Then
                        xmlDataSet.ReadXml(My.Settings.path_custom_data & dataFilename, System.Data.XmlReadMode.ReadSchema)
                    Else
                        MsgBox(dataFilename & " does not exist ")
                        Exit Sub
                    End If
                    dataFilename = My.Settings("xmlAttrApplications")
                    If File.Exists(My.Settings.path_custom_data & dataFilename) = True Then
                        xmlDataSet.ReadXml(My.Settings.path_custom_data & dataFilename, System.Data.XmlReadMode.ReadSchema)
                    Else
                        MsgBox(dataFilename & " does not exist ")
                        Exit Sub
                    End If

                    _clsData.loadAppConnTable(xmlDataSet.Tables("dbo_appConnections"))
                    _clsData.loadAppSolTable(xmlDataSet.Tables("dbo_appSolutions"))
                    _clsData.loadAppTable(xmlDataSet.Tables("dbo_AttrApplications"))


            End Select


            ' clear the list of solutions on the page
            dictPageSolutions = Nothing
            dictPageSolutions = New Dictionary(Of Int32, String)

            ' clear the list of applications on the page
            dictPageApplications = Nothing
            dictPageApplications = New Dictionary(Of Short, Int32)

            lstSolutions.Items.Clear()
            btnAdd.Enabled = False
            btnRemove.Enabled = False

            lstApplications.Items.Clear()

            '
            ' check the existing drawing page to see if it has content
            '
            Dim visShape As Visio.Shape = Nothing
            Dim intAppKey As Int32 = -1
            Dim docSheet As Visio.Shape = Me.drawingDocument.DocumentSheet
            Dim strLayer As String = ""
            If docSheet.CellExists("user.solution", False) = True Then
                Dim strSolution = LCase(docSheet.Cells("user.solution").ResultStr(""))
                If strSolution = "dc_rack" Then
                    If docSheet.CellExists("user.diagram", False) = True Then
                        Dim strDiagram = LCase(docSheet.Cells("user.diagram").ResultStr(""))
                        If strDiagram = "appconnectivity" Then
                            ' load the page applications
                            For Each visShape In Me.drawingPage.Shapes
                                If visShape.CellExists("prop.appKey", False) = True Then
                                    intAppKey = CInt(visShape.Cells("prop.appKey").ResultIU)
                                    dictPageApplications.Add(visShape.ID, intAppKey)
                                End If
                            Next visShape

                            ' now add the "solutions" layers
                            For Each visLayer As Visio.Layer In Me.drawingPage.Layers
                                strLayer = visLayer.NameU
                                Dim layerQuery = From solution In _clsData.m_ds.Tables(dc_racktables.tblAppSolution.ToString).AsEnumerable() _
                                        Where solution!appsolName = strLayer _
                                        Select solution

                                'execute and find only one solution in the table with that key
                                If layerQuery.Count = 1 Then
                                    For Each s In layerQuery
                                        If dictPageSolutions.ContainsKey(s.Item("appsolkey")) = False Then
                                            dictPageSolutions.Add(s.Item("appsolKey"), strLayer)
                                        End If
                                    Next s
                                End If
                            Next visLayer
                            ' end test for appconnectivity
                        End If
                    End If
                End If
                ' end begin checking to see if the active page one of our solution pages
            End If

            ' finally load the solutions list
            Dim solutionQuery = From solution In _clsData.m_ds.Tables(dc_racktables.tblAppSolution.ToString).AsEnumerable() _
                    Select solution
            'execute and find only one component in the table with that key
            If 0 < solutionQuery.Count Then
                For Each s In solutionQuery
                    lstSolutions.Items.Add(s.Item("appsolName").ToString)
                Next s
            End If

        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    ' Reads a workbook and returns a collection of worksheet names as a 
    ' dictionary
    '
    Private Function readExcelWorksheetList _
        (ByVal strWorkbook As String) _
        As Dictionary(Of Int16, String)

        Dim dictReturn As Dictionary(Of Int16, String) = New Dictionary(Of Int16, String)


        If (strWorkbook Is Nothing) Then
            Throw New System.ArgumentNullException("strWorkbook", _
                "Workbook is Null.")
            GoTo ExitFunction
        End If

        If File.Exists(strWorkbook) = False Then
            MsgBox("Workbook (" & strWorkbook & ") not found")
            GoTo ExitFunction
        End If

        Dim objExcel As Excel.Application
        Dim objWorkBook As Excel.Workbook
        Dim objWorkSheets As Excel.Worksheet
        Dim ExcelSheetName As String = ""
        objExcel = CreateObject("Excel.Application")
        objWorkBook = objExcel.Workbooks.Open(strWorkbook)
        Dim intX As Integer = 1
        For Each objWorkSheets In objWorkBook.Worksheets
            dictReturn.Add(intX, objWorkSheets.Name)
            intX = intX + 1
        Next

        objExcel.Quit()
        objExcel = Nothing

ExitFunction:

        Return dictReturn

    End Function

    '
    ' read a worksheet and return a datatable
    '
    Private Function readExcelWorksheet _
            (ByVal strWorkBook As String, _
            ByVal strWorkSheet As String) _
            As System.Data.DataTable


        Dim dtReturn As System.Data.DataTable = Nothing

        Try

            If (strWorkBook Is Nothing) _
                Or strWorkBook = "" Then
                Throw New System.ArgumentNullException("strWorkbook", _
                    "Workbook is Null.")
                GoTo ExitFunction
            End If

            If File.Exists(strWorkBook) = False Then
                MsgBox("Workbook (" & strWorkBook & ") not found")
                GoTo ExitFunction
            End If

            Dim DS As DataSet
            Dim MyCommand As OleDb.OleDbDataAdapter
            Dim MyConnection As OleDb.OleDbConnection
            Dim strConnection As String = "Provider=Microsoft.ACE.OLEDB.12.0;" _
                                          & "Data Source=" & strWorkBook & ";" _
                                          & "Extended Properties=" & """Excel 12.0 Xml;HDR=YES""" & ";"
            MyConnection = New OleDb.OleDbConnection(strConnection)
            MyCommand = New OleDb.OleDbDataAdapter( _
                         "select * from [" & strWorkSheet & "$]", MyConnection)
            DS = New System.Data.DataSet()
            MyCommand.Fill(DS)
            dtReturn = DS.Tables(0)
            dtReturn.TableName = strWorkSheet
            MyConnection.Close()

ExitFunction:

        Catch oledb As OleDbException

            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(oledb, "Database Policy")
            If (rethrow) Then
                Throw
            End If


        Catch ex As Exception

            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

        Return dtReturn

    End Function

    '
    ' 
    '
    Private Sub saveVisioDocumentDialog()



        Try

            Dim visDoc As Microsoft.Office.Interop.Visio.Document = Me.drawingDocument

            ' flag the document as one of ours
            Dim docsheet As Microsoft.Office.Interop.Visio.Shape = visDoc.DocumentSheet
            _clsVisio.ForceUserProperty(docsheet, "Solution", "DC_Rack")
            _clsVisio.ForceUserProperty(docsheet, "Diagram", "LinkAttributes")

            SaveFileDialog.Filter = "vsd files (*.vsd)|*.vsd|All files (*.*)|*.*"
            SaveFileDialog.FilterIndex = 1
            SaveFileDialog.RestoreDirectory = True

            Dim dlgResult As DialogResult = SaveFileDialog.ShowDialog

            If dlgResult = DialogResult.OK Then
                If _clsData._BlnDR = vbTrue Then
                    Dim resultMsg As MsgBoxResult = MsgBox("Save Hidden Data?", MsgBoxStyle.YesNo, "SaveHiddenData")
                    If resultMsg = MsgBoxResult.No Then
                        ' get rid of recordsets, masters, and personal information
                        visDoc.RemoveHiddenInformation(Microsoft.Office.Interop.Visio.VisRemoveHiddenInfoItems.visRHIDataRecordsets + _
                                                       Microsoft.Office.Interop.Visio.VisRemoveHiddenInfoItems.visRHIMasters + _
                                                       Microsoft.Office.Interop.Visio.VisRemoveHiddenInfoItems.visRHIPersonalInfo)

                    End If

                End If


                visDoc.SaveAsEx(SaveFileDialog.FileName, Microsoft.Office.Interop.Visio.tagVisOpenSaveArgs.visSaveAsWS + _
                                Microsoft.Office.Interop.Visio.tagVisOpenSaveArgs.visSaveAsListInMRU)

            Else

                MsgBox("Save Cancelled")

            End If

        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


        System.GC.Collect()

    End Sub

    '
    '
    '
    Private Sub openDocumentDialog()



        Try

            OpenFileDialog.InitialDirectory = "c:\"
            OpenFileDialog.FileName = "*.vsd"
            OpenFileDialog.Filter = "visio drawings (*.vsd)|*.vsd|All files (*.*)|*.*"
            OpenFileDialog.FilterIndex = 1
            OpenFileDialog.RestoreDirectory = True

            Dim strPath As String = ""
            Dim dlgResult As System.Windows.Forms.DialogResult = OpenFileDialog.ShowDialog

            If dlgResult = System.Windows.Forms.DialogResult.OK Then

                Me.drawingWindow.SelectAll()
                Dim selGroup As Visio.Selection = drawingWindow.Selection
                selGroup.Delete()

                Me.drawingControl.Src = OpenFileDialog.FileName

                Me.drawingWindow = Me.drawingControl.Window
                Me.drawingApplication = Me.drawingControl.Window.Application
                Me.drawingDocument = Me.drawingApplication.ActiveDocument
                Me.drawingPage = Me.drawingApplication.ActivePage

                ' load it from the included xml files
                loadDictionariesFromPage()

                ' flag it as already having been saved
                Me.drawingDocument.Saved = True

            End If

        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub


#End Region

#Region " Drawing "


    '
    ' this uses the solutions/app dictionary which is initialized by selecting a solution
    ' that is not currently loaded (not in page solutions or has a layer identified)
    '
    Private Sub AddApplicationsToPage(ByVal strLayer As String)


        Try


            ' current solution applications should be in dictSolApps
            Dim intKey As Int32 = -1
            Dim strValue As String = ""

            Dim visShape As Visio.Shape
            Dim visCell As Visio.Cell

            Dim randomLocation As Random = New Random

            ' this is the string that will give us the double click event that we want to use
            ' to get off of the page
            Dim strDblClick As String = "=RUNADDONWARGS("
            strDblClick = strDblClick & """QueueMarkerEvent"""
            strDblClick = strDblClick & ","
            strDblClick = strDblClick & """/dc_rack /cmd=4"""
            strDblClick = strDblClick & ")"

            Dim strShapeType As String = "server"
            Dim strShapeName As String = ""
            Dim shpContainer As Visio.Shape = Nothing
            ' go through the applications in the current solution dictionary
            For Each solKvp As KeyValuePair(Of Int32, String) In dictSolApps
                intKey = solKvp.Key        ' the application key
                strValue = solKvp.Value    ' the application name

                ' has this application been put onto the page
                If dictPageApplications.ContainsValue(intKey) = False Then

                    Dim applicationQuery = From application In _clsData.m_ds.Tables(DC_RackTables.tblAttrApplication.ToString).AsEnumerable() _
                                           Where application!appkey = intKey
                                          Select application

                    ' we were able to find the application
                    _clsVisio.drawingPage = drawingPage
                    _clsVisio.drawingDocument = drawingPage.Document

                    If applicationQuery.Count = 1 Then

                        For Each a In applicationQuery
                            strShapeName = ""
                            shpContainer = Nothing
                            strShapeType = a.Item("appShape")


                            visShape = _clsVisio.DropMasterOnPage _
                                            (drawingPage, strShapeType, stencilNameU, _
                                            0, 0, "in.")

                            ' clear any existing shape data from the shape
                            _clsVisio.deleteShapeData(visShape)
                            visShape.Name = intKey.ToString
                            visShape.NameU = intKey.ToString
                            visShape.Text = strValue

                            _clsVisio.ForceUserProperty(visShape, "AttrKey", "appKey_" & CStr(a.Item("appKey")))

                            visCell = visShape.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowEvent, VisCellIndices.visEvtCellDblClick)
                            visCell.FormulaU = strDblClick

                            _clsVisio.ForceShapeData(visShape, "appKey", intKey.ToString, "attrApp")
                            _clsVisio.ForceShapeData(visShape, "appName", strValue, "attrApp")

                            _clsVisio.addShapeToLayer(drawingPage, visShape, strLayer, True)
                            ' all apps for testing
                            ' _clsVisio.AddShapeToLayer(drawingPage, visShape, "allApps", True)

                            ' add the shapeid and associated application key
                            dictPageApplications.Add(visShape.ID, intKey)

                            ' now put it in a container with a matching name
                            strShapeName = Replace(strShapeType, " ", "_")
                            shpContainer = _clsVisio.addContainerToPage(masterContainerNameU, strShapeName, strShapeType)
                            If shpContainer IsNot Nothing Then
                                _clsVisio.AddShapeToContainer(shpContainer, visShape)
                            End If
                        Next a
                        ' end test to see if we found single application
                    End If

                Else
                    ' the application was found in the page application dictionary so assign it to another
                    ' layer
                    For Each appKvp As KeyValuePair(Of Short, Int32) In dictPageApplications
                        If appKvp.Value = intKey Then
                            visShape = Me.drawingPage.Shapes.ItemFromID(appKvp.Key)
                            _clsVisio.addShapeToLayer(drawingPage, visShape, strLayer, True)
                            Exit For
                        End If
                    Next appKvp
                End If

            Next solKvp



        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        'layoutContainers()

    End Sub

    '
    '
    '
    Private Sub connectSolutionApplications(ByVal strLayer As String)

        Dim intApplAKey As Int32 = -1
        Dim intApplBKey As Int32 = -1
        Dim shtApplAId As Short = -1
        Dim shtApplBId As Short = -1
        Dim shpApplA As Visio.Shape = Nothing
        Dim shpApplB As Visio.Shape = Nothing
        Dim kvpa As KeyValuePair(Of Short, Int32)
        Dim kvpb As KeyValuePair(Of Short, Int32)

        Try

            _clsVisio.drawingPage = drawingApplication.ActivePage

            '
            ' get a list of unique application keys for the selected solution
            '
            Dim connectionQuery = From connects In _clsData.m_ds.Tables(dc_racktables.tblAppConnection.ToString).AsEnumerable() _
                                  Where connects!appconSolKey = _CurrSolution _
                                  Select connects

            If 0 < connectionQuery.Count Then
                For Each c In connectionQuery

                    intApplAKey = c.Item("appconAppAKey")
                    intApplBKey = c.Item("appconAppBKey")

                    For Each kvpa In dictPageApplications
                        If kvpa.Value = intApplAKey Then
                            shtApplAId = kvpa.Key
                            Exit For
                        End If
                    Next

                    For Each kvpb In dictPageApplications
                        If kvpb.Value = intApplBKey Then
                            shtApplBId = kvpb.Key
                            Exit For
                        End If
                    Next

                    shpApplA = Me.drawingPage.Shapes.ItemFromID(shtApplAId)
                    shpApplB = Me.drawingPage.Shapes.ItemFromID(shtApplBId)

                    Dim shpConnector As Visio.Shape = Nothing
                    shpConnector = _clsVisio.ConnectWithDynamicGlueAndConnector(shpApplA, shpApplB)

                    _clsVisio.ForceShapeData(shpConnector, "appconKey", c.Item("appconKey").ToString, "appCon")
                    _clsVisio.ForceShapeData(shpConnector, "appconSolKey", c.Item("appconSolKey"), "appCon")
                    _clsVisio.ForceShapeData(shpConnector, "appconAppAKey", c.Item("appconAppAKey").ToString, "appCon")
                    _clsVisio.ForceShapeData(shpConnector, "appconAppBKey", c.Item("appconAppBKey").ToString, "appCon")


                    If shpConnector IsNot Nothing Then
                        _clsVisio.addShapeToLayer(drawingPage, shpConnector, strLayer, True)
                    End If


                Next c

            End If

            Dim visLayer As Visio.Layer = Nothing
            ' delete the connector level as well if it is there
            Try
                visLayer = Me.drawingPage.Layers.Item("Connector")
            Catch
            End Try
            If visLayer IsNot Nothing Then
                ' unlock it just in case
                visLayer.CellsC(visCellIndices.visLayerLock).FormulaU = "0"
                ' delete it
                visLayer.Delete(1)
            End If

            Me.drawingWindow.DeselectAll()

        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub


    '
    '
    '
    Private Sub initContainerSize(ByVal visShape As Visio.Shape)

        Try


            ' setup the initial positions (probably a waste of code since the autoposition will overwrite it)
            Dim visCell As Visio.Cell = Nothing
            visCell = visShape.Cells("height")
            visCell.FormulaU = "User.dcr_acContHeight"
            visCell = visShape.Cells("width")
            visCell.FormulaU = "User.dcr_acContWidth"
            visCell = visShape.Cells("pinY")
            visCell.Formula = "ThePage!PageHeight-User.dcr_acContMargin-(User.dcr_acIndex*Height)"
            visCell = visShape.Cells("pinX")
            visCell.FormulaU = "User.dcr_acContMargin + (Width / 2)"

            _clsVisio.drawingWindow = drawingControl.Window
            _clsVisio.layoutShapesWithinContainer(visShape)

        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try
    End Sub




    '
    ' 
    '
    Public Sub layoutContainers()


        Try

            Me.btnRemove.Enabled = False
            Me.btnAdd.Enabled = False

            Dim shpContainer As Visio.Shape = Nothing
            Dim intIndex As Int16 = 0
            Dim visCell As Visio.Cell = Nothing
            Dim visPageSheet As Visio.Shape = Me.drawingPage.PageSheet
            Dim dblPageHeight As Double = visPageSheet.Cells("PageHeight").ResultIU
            Dim dblWidth As Double = 0
            Dim pinX As Double = 0
            Dim pinY As Double = 0



            ' get the primary containers
            For Each containerID In Me.drawingPage.GetContainers(VisContainerNested.visContainerExcludeNested)
                shpContainer = Me.drawingPage.Shapes.ItemFromID(containerID)
                'drawingWindow.Select(drawingWindow.Page.Shapes.ItemFromID(containerID), visSelect)

                pinY = dblPageHeight - ((intIndex * 1.5) + dblContainerMargin)
                dblWidth = shpContainer.Cells("Width").ResultIU
                pinX = (dblWidth / 2) + dblContainerMargin
                shpContainer.Cells("PinY").Formula = pinY
                shpContainer.Cells("PinX").Formula = pinX

                intIndex = intIndex + 1

            Next


        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


        btnAdd.Enabled = False
        btnRemove.Enabled = False

    End Sub




#End Region

#Region " Form Events "


    '
    '
    '
    Private Sub frmAppConnectivity_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.rptViewer.RefreshReport()

    End Sub

    '
    '
    '
    Private Sub FileExitToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles FileExitToolStripMenuItem.Click
        Me.Close()
    End Sub

    '
    ' open a visio document
    '
    Private Sub FileLoadToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles FileLoadToolStripMenuItem.Click
        openDocumentDialog()
    End Sub

    '
    ' save the visio document
    '
    Private Sub FileSaveToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles FileSaveToolStripMenuItem.Click
        saveVisioDocumentDialog()
    End Sub

    '
    ' load data from sql source
    '
    Private Sub DataSQLToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataSQLToolStripMenuItem.Click


        Me.drawingWindow.SelectAll()
        Dim selGroup As Visio.Selection = drawingWindow.Selection
        selGroup.Delete()

        Me.DataExcelToolStripMenuItem.Checked = False
        Me.DataXMLToolStripMenuItem.Checked = False
        Me.DataSQLToolStripMenuItem.Checked = True
        loadDictionariesFromPage("sql")

    End Sub

    '
    ' load data from excel
    '
    Private Sub DataExcelToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataExcelToolStripMenuItem.Click

        Try


            ' if nothing has been drawn then make sure we do not error out prematurely
            Try
                Me.drawingWindow.SelectAll()
                Dim selGroup As Visio.Selection = drawingWindow.Selection
                selGroup.Delete()
            Catch com As COMException
            End Try


            Me.DataExcelToolStripMenuItem.Checked = True
            Me.DataXMLToolStripMenuItem.Checked = False
            Me.DataSQLToolStripMenuItem.Checked = False
            loadDictionariesFromPage("excel")



        Catch ex As Exception
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try
    End Sub

    '
    ' load data from xml 
    '
    Private Sub DataXMLToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataXMLToolStripMenuItem.Click


        Me.drawingWindow.SelectAll()
        Dim selGroup As Visio.Selection = drawingWindow.Selection
        selGroup.Delete()

        Me.DataExcelToolStripMenuItem.Checked = False
        Me.DataXMLToolStripMenuItem.Checked = True
        Me.DataSQLToolStripMenuItem.Checked = False

        loadDictionariesFromPage("xml")

    End Sub

    '
    ' about form 
    '
    Private Sub AboutToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click

        Dim frmAbout As frmAboutBox = New frmAboutBox
        frmAbout.ShowDialog()
        frmAbout.Dispose()
        frmAbout = Nothing

    End Sub

    '
    '
    '
    Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Try


            Dim strSolution As String = ""

            drawingWindow = drawingControl.Window

            If lstSolutions.SelectedItems.Count = 1 Then
                strSolution = lstSolutions.SelectedItem

                ' already listed in page dictionary
                If dictPageSolutions.ContainsValue(strSolution) = True Then
                    ' already in the page solutions
                    btnAdd.Enabled = False
                    Exit Sub
                End If

                Dim intAppSolKey As Int32 = -1
                ' first get the solution Key so that we can look for connections
                Dim solutionQuery = From solution In _clsData.m_ds.Tables(DC_RackTables.tblAppSolution.ToString).AsEnumerable() _
                            Where solution!appsolName = strSolution _
                            Select solution

                'execute and find only one solution in the table with that key
                If solutionQuery.Count = 1 Then
                    For Each s In solutionQuery
                        intAppSolKey = s.Item("appsolKey")
                    Next s
                Else
                    ' no solution by this name with a key
                    btnAdd.Enabled = False
                    Exit Sub
                End If

                ' get the layer information
                Dim visLayer As Visio.Layer = Nothing
                Try
                    visLayer = Me.drawingPage.Layers(strSolution)
                Catch ex As Exception
                End Try
                ' this should not happen (it wasn't in the page solutions dictionary
                If visLayer Is Nothing Then
                    _clsVisio.AddLayerToPage(drawingPage, strSolution)
                End If

                ' add it to the list of solutions on the page
                dictPageSolutions.Add(intAppSolKey, strSolution)

                ' add the applications
                AddApplicationsToPage(strSolution)

                ' connect them 
                connectSolutionApplications(strSolution)

                drawingWindow.DeselectAll()

                ' end test for only one selected
            End If


        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        layoutContainers()

        ' clear the current solution applications dictionary
        dictSolApps = Nothing
        dictSolApps = New Dictionary(Of Int32, String)
        ' clear the selected solutions
        clearListSelections(lstSolutions)
        ' clear the applications list
        lstApplications.Items.Clear()

        Me.btnRemove.Enabled = False
        Me.btnAdd.Enabled = False


    End Sub

    '
    '
    '
    Private Sub btnRemove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemove.Click
        Try


            Dim strSolution As String = ""
            If lstSolutions.SelectedItems.Count = 1 Then

                strSolution = lstSolutions.SelectedItem

                deleteSolutionLayer(strSolution)

            End If


        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        clearListSelections(lstSolutions)


    End Sub


    '
    ' if the lstSolutions control is clicked make sure we show the reports
    '
    Private Sub lstSolutions_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstSolutions.Click

        loadItemReport("appsolkey")

    End Sub

    '
    ' if the lstSolutions selection changes, load the appropriate applications into the lstApplications control
    '
    Private Sub lstSolutions_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstSolutions.SelectedIndexChanged



        Dim strLi As String


        Try


            strLi = CType(lstSolutions.SelectedItem, String)

            ' make sure we clear the list of items
            Me.lstApplications.Items.Clear()

            If lstSolutions.SelectedIndices.Count = 1 Then
                If dictPageSolutions.ContainsValue(strLi) = True Then
                    btnRemove.Enabled = True
                    btnAdd.Enabled = False
                Else
                    btnRemove.Enabled = False
                    btnAdd.Enabled = True
                    loadSolutionApplicationsData(strLi)
                End If
            End If


        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub


    '
    ' if the lstApplications is clicked show the connections table
    '
    Private Sub lstApplications_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstApplications.Click

        loadItemReport("appconnkey")

    End Sub


#End Region

#Region " Visio Events "

    '
    ' 
    '
    Private Sub mouseUp_EventHandler(ByVal mouseButton As Integer, _
                ByVal buttonState As Integer, _
                ByVal clickLocationX As Double, _
                ByVal clickLocationY As Double, _
                ByRef cancelProcessing As Boolean)

        Const tolerance As Double = 0.0001

        Dim clickedShapes As Microsoft.Office.Interop.Visio.Selection = Nothing
        Dim message As New System.Text.StringBuilder()

        Try

            ' Check if the left mouse mouseButton caused this event
            ' to occur.
            If mouseButton = CInt(Microsoft.Office.Interop.Visio. _
                VisKeyButtonFlags.visMouseLeft) Then

                ' Get the list of shapes at the click location.
                clickedShapes = getMouseClickShapes( _
                    drawingWindow.PageAsObj, clickLocationX, _
                    clickLocationY, tolerance)

                ' Check if any shapes were found.
                If ((Not clickedShapes Is Nothing) And _
                    (clickedShapes.Count = 1)) Then

                    ' Show the name of shape.
                    message.Append(clickedShapes.Item(1).NameU & _
                        System.Environment.NewLine)

                    If clickedShapes.Item(1).CellExists("user.attrkey", False) = True Then
                        Dim strAttrCell As String = clickedShapes.Item(1).Cells("user.attrkey").ResultStr("")
                        ' parse out the user cell
                        ' first string is the record field name
                        ' second string is the record key
                        Dim instance As String = strAttrCell
                        Dim charSeparators() As Char = {"_"c}
                        Dim count As Integer = 2
                        Dim options As StringSplitOptions = StringSplitOptions.None
                        Dim returnValue As String()

                        returnValue = instance.Split(charSeparators, _
                                count, options)

                        'If (drawingWindow.Application.AlertResponse = 0) Then
                        '    System.Windows.Forms.MessageBox.Show(message.ToString())
                        'End If

                        ' based on the field name load the reportviewer
                        loadItemReport(returnValue(0))


                    End If ' test for attrkey cell

                End If
            End If

        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    ' find the shape that was acted on 
    '
    Private Shared Function getMouseClickShapes( _
                ByVal clickedPage As Microsoft.Office.Interop.Visio.Page, _
                ByVal clickedLocationX As Double, _
                ByVal clickedLocationY As Double, _
                ByVal tolerance As Double) _
                As Microsoft.Office.Interop.Visio.Selection

        Dim clickedShapes As Microsoft.Office.Interop.Visio.Selection = Nothing

        Try

            ' Use the SpatialSearch method of the page to get the list
            ' of shapes at the location.
            clickedShapes = clickedPage.SpatialSearch( _
                clickedLocationX, clickedLocationY, _
                CInt(Microsoft.Office.Interop.Visio. _
                VisSpatialRelationCodes.visSpatialContainedIn), _
                tolerance, _
                CInt(Microsoft.Office.Interop.Visio. _
                VisSpatialRelationFlags.visSpatialFrontToBack))


        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


        Return clickedShapes

    End Function



#End Region








End Class
